package com.cdpowernode.pncrm.service.impl;

import com.cdpowernode.pncrm.exception.CrmException;
import com.cdpowernode.pncrm.javabean.User;
import com.cdpowernode.pncrm.javabean.UserVo;
import com.cdpowernode.pncrm.service.UserService;
import com.cdpowernode.pncrm.mapper.UserMapper;
import com.cdpowernode.pncrm.utils.CrmDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userVo 封装了用户的登录请求中所有的请求数据
     * @param ip 如果登录成功用户请求的用户名对应的User对象
     * @return 返回查到的用户信息
     */
    @Override
    public User login(UserVo userVo, String ip) {
        //根据用户输入的用户名查找数据中对应的信息
        User user = userMapper.queryUserByAct(userVo.getLoginAct());
        //判断用户名是否存在
        if (user == null){
            throw new CrmException("用户名不存在!");
        }
        //判断密码是否正确
        if (!user.getLoginPwd().equals(userVo.getLoginPwd())){
            throw new CrmException("用户名或密码错误!");
        }
        //判断用户是否过期
        if (CrmDateUtil.dateToString(new Date()).compareTo(user.getExpireTime()) > 0){
            throw new CrmException("账号已过期!");
        }
        //判断用户是否被锁定
        if (user.getLockState().equals("0")){
            throw new CrmException(("账户被锁定!"));
        }
        String[] ipArr = user.getAllowIps().split(",");
        List<String> ipList = Arrays.asList(ipArr);
        if (!ipList.contains(ip)){
            throw new CrmException("ip受限!");
        }
        return user;
    }

    @Override
    public List<User> findAll() {
        return userMapper.queryAllUsers();
    }
}




